angular.module('imgApp').directive('pagination', ['$rootScope', function($rootScope) {
	
	const PAGINATION = 30;
	const MAX_PAGES_NUM = 5;
	
	function getPages(len, pagination) {
		pagination = pagination || PAGINATION;
		return len % pagination > 0? parseInt(len / pagination) + 1: parseInt(len / pagination);
	}
	
	function toPage(page, totalPages, pages, allPages, pagination, maxpage) {
		pagination = pagination || PAGINATION;
		maxpage = maxpage || MAX_PAGES_NUM;
		var p = parseInt(page);
		var viewArr = [];
		if (p > 0 && p <= totalPages) {
			viewArr = allPages.slice((p - 1) * pagination, p * pagination);
			if (needUpdatePages(p, pages)) {
				pages = genPageNum(p, maxpage, totalPages);
			}
			window.location.hash = "#here";
			return {
				curPage: p,
				pages: pages,
				viewArr: viewArr
			};
		} else {
			alert("不在页码范围内！");
			return false;
		}
	}
	
	function prePage(curPage) {
		if(curPage > 1) {
			curPage -= 1;
		} else {
			alert("到头了！");
		}
		return curPage;
	}

	function nextPage(curPage, pn) {
		if(curPage < pn) {
			curPage += 1;
		} else {
			alert("到头了！");
		}
		return curPage;
	}
	
	function needUpdatePages(curPage, pages) {
		var start = pages[0],
			end = pages[pages.length - 1];
		if (curPage >= start && curPage <= end) {
			return false;
		} else {
			return true;
		}
	}
	
	function genPageNum(curPage, n, totalPages) {
		n = n || MAX_PAGES_NUM;
		var pages = [],
			integer = parseInt(curPage / n),
			start = curPage % n != 0 ? (integer * n + 1) : ((integer - 1) * n + 1),
			end = curPage % n != 0 ? (integer + 1) * n : integer * n;
		if(end > totalPages) end = totalPages;
		for(var i = start; i <= end; i++) {
			pages.push(i);
		}
		return pages;
	}
	
	function linkFn($scope, $element, $attrs) {
		$attrs.$observe('data', function(val) {	
			if (val && val.length > 0) {
				var tp = JSON.parse(val);
				$scope.pn = getPages(tp.length, PAGINATION);
				$scope.curPage = 1;
				var viewArr = tp.slice(0, PAGINATION);
				$scope.view = viewArr;
				$scope.redirect = '';
				$scope.pages = genPageNum($scope.curPage, MAX_PAGES_NUM, $scope.pn);
				console.log($scope.pages);
				$scope.prePage = function() {
					var cp = $scope.curPage;
					$scope.curPage = prePage($scope.curPage);
					if ($scope.curPage != cp) {
						$scope.toPage($scope.curPage);
					}	
				}
				$scope.nextPage = function() {
					var cp = $scope.curPage;
					$scope.curPage = nextPage($scope.curPage, $scope.pn);
					if($scope.curPage != cp) {
						$scope.toPage($scope.curPage);
					}
				}
				
				$scope.toPage = function(p) {
					var result = toPage(p, $scope.pn, $scope.pages, tp, PAGINATION, MAX_PAGES_NUM);
					if(result) {
						$scope.curPage = result.curPage;
						$scope.pages = result.pages;
						$scope.view = result.viewArr;
					}
				}
			}
		})
	}
	
	return {
		restrict: 'AE',
		templateUrl: 'lib/directive/pagination/pagination.html',
		scope: {
			data: '@',
			view: '='
		},
		link: linkFn
	};
}]);